import { ITodoData } from "../../../typings"
import Component from "./Component"

export interface IListOpionts {
    wrapperEl: HTMLElement
    todoData: ITodoData[]
}

class List extends Component {
    private wrapperEl: HTMLElement
    private static todoData: ITodoData[]
    constructor(options: IListOpionts) {
        super()
        this.wrapperEl = options.wrapperEl
        List.todoData = options.todoData
    }
    public render() {
        this.wrapperEl.innerHTML += Component.listView(List.todoData)
    }

    public bindEvent() {
        const oTodoList: HTMLElement = document.querySelector('.todo-list')
        oTodoList.addEventListener('click', this.handleTodoListClick.bind(this), false)
    }

    public static addItem(val: string) {
        const todoItem: ITodoData = {
            id: Math.random() + new Date().getTime(),
            content: val,
            completed: false
        }
        List.todoData.push(todoItem)
        document.querySelector('.todo-list').innerHTML = Component.listView(List.todoData)
    }

    private handleTodoListClick(e: MouseEvent) {
        const tar = e.target as HTMLElement
        const tagName = tar.tagName.toLowerCase()
        const oTodoItems: HTMLCollection = document.getElementsByClassName('todo-item')

        if (['input', 'button'].includes(tagName)) {
            const id: number = Number(tar.dataset.id)
            switch (tagName) {
                case 'input':
                    this._handleInputClick(id, oTodoItems)
                    break;
                case 'button':
                    this._handleBtnClick(id)
                    break
                default:
                    break
            }
        }

    }
    private _handleInputClick(id: number, oTodoItems: HTMLCollection) {
        List.todoData = List.todoData.map((todo: ITodoData, index: number) => {
            if (todo.id === id) {
                todo.completed = !todo.completed
                oTodoItems[index].querySelector('span').style.textDecoration = todo.completed ? 'line-through' : ''
            }
            return todo
        })
    }
    private _handleBtnClick(id: number) {
        List.todoData = List.todoData.filter((todo: ITodoData) => todo.id !== id)
        document.querySelector('.todo-list').innerHTML = Component.listView(List.todoData)
    }

}
export default List